﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Lister;
using System.IO;
using COFE.Core.Utils;
using System.Diagnostics;
using COFE.Core;
using COFE.Core.Profile;

namespace COFE.Web
{
    /// <summary>
    /// Represent a web user.
    /// </summary>
    public class UserServiceProfile : IUserServiceProfile
    {

        #region Constructor

        public UserServiceProfile(IUserProfile2 userprofile)
        {

            _userProfile = userprofile;            

            Debug.WriteLine(System.Web.Security.FormsAuthentication.FormsCookieName);
        }

        #endregion

        #region Methods

        #region Entry

        public Entry LookupEntry(string path)
        {
            IFileSystemInfo fsi = _userProfile.ParsePath(path);

            Entry retEntry = Entry.FromCofeEntry(fsi);
            return retEntry;
        }

        /// <summary>
        /// Find an entry using it's guid.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Entry LookupEntry(Guid id)
        {
            Entry retEntry = Entry.FromCofeEntry(_userProfile.ParseGuid(id));
            return retEntry;
        }

        public EntryList ListEntry(Entry parentEntry, string filterStr)
        {
            IDirectoryInfo parentDirectory = 
                COFEShared.CurrentUserProfile.TryParseGuid(parentEntry.ID) as IDirectoryInfo;
            if (parentDirectory == null)
                throw new System.IO.FileNotFoundException();            
            COFE.Core.AutoEntryList ael;
            ael = new COFE.Core.AutoEntryList("list", parentDirectory, "subdir:false " + filterStr);
            return new CoreEntryList(ael);
        }

        public PropertyPair GetResource(Entry entry, string resourceName)
        {
            return entry.GetProperty(resourceName);
        }

        public Stream GetFileStream(Entry entry)
        {
            return entry.OpenStream();
        }

        public void SetFileStream(Entry entry, Stream stream)
        {
            using (Stream fileStream = entry.OpenStream(true))
            {
                StreamUtils.CopyStream(stream, fileStream, false, false, false);
            }
        }
        #endregion
       

        #endregion

        #region Data

        private IUserProfile2 _userProfile;        

        #endregion

        #region Public Properties

        /// <summary>
        /// Username of the current user.
        /// </summary>
        public string UserName { get { return _userProfile.UserName; } }

        /// <summary>
        /// UserProfile of the current user, which should be IUserDBProfile.
        /// </summary>
        public IUserProfile2 UserProfile { get { return _userProfile; } }
   
        #endregion


        
    }
}
